﻿using System.Runtime.CompilerServices;

namespace zijian666.Updater;
public static class Helper
{
    /// <summary>
    /// 读取文本内容，支持本地文件路径和HTTP/HTTPS URL
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static async ValueTask<string> ReadString(string str)
    {
        if (Uri.TryCreate(str, UriKind.RelativeOrAbsolute, out var uri))
        {
            if (!uri.IsAbsoluteUri || uri.Scheme is "file")
            {
                var basePath = AppContext.BaseDirectory;
                var fullPath = Path.GetFullPath(Path.Combine(basePath, str));
                if (File.Exists(fullPath))
                {
                    return await File.ReadAllTextAsync(fullPath);
                }
                return fullPath + "!! 文件不存在";
            }

            if (uri.Scheme is "http" or "https")
            {
                using var client = new HttpClient();
                return await client.GetStringAsync(uri);
            }
        }

        return str;
    }


    /// <summary>
    /// 同步执行异步方法
    /// </summary>
    public static T Sync<T>(Func<Task<T>> func)
    {
        return Task.Run(() => func()).GetAwaiter().GetResult();
    }


    /// <summary>
    /// 同步执行异步方法
    /// </summary>
    public static void Sync(Func<Task> func)
    {
        Task.Run(() => func()).GetAwaiter().GetResult();
    }
}
